package com.kingcore.director.search.ui;



import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.util.Version;

public class LocalFileIndexManager {
	Logger logger = Logger.getLogger(LocalFileIndexManager.class.getName());
	private String indexStorePath;
	private IndexReader indexReader;
	
	public LocalFileIndexManager(String indexStorePath) throws IOException {
		//indexStorePath = "E:/Woo_Java/Prj_wzwen_director/tmp/index/localFileSystem";
		
		this.indexStorePath = indexStorePath;
		try {
			this.indexReader = IndexReader.open(indexStorePath);
			this.indexStorePath = indexStorePath; 
		} catch (IOException e) {
			logger.debug("索引文件不存在: " + indexStorePath);
			throw e;
		}
	}
	
	/** 查询索引 */
	public List<Document> query(String queryWord, String[] indexFields, int startRow, int endRow) {
		List<Document> ret = new ArrayList<Document>();
		Searcher searcher = null;
		Query q = null;
		Hits h = null;
		
		try {	
			searcher = new IndexSearcher(this.indexReader);
			String[] fields = indexFields;
			BooleanClause.Occur[] flags = new BooleanClause.Occur[indexFields.length];
			for(int i = 0; i < flags.length; i++) {
				flags[i] = BooleanClause.Occur.SHOULD;
			}
			//Sort sort = new Sort("lastModifiedTime", true);
			q = MultiFieldQueryParser.parse(Version.LUCENE_29,queryWord, fields, flags, LocalFileIndexBuilder.ANALYZER2);
			h = searcher.search(q);  //, sort
			//如果用分词切分的结果找不到，使用一元切分
			if(h.length() == 0) {
				q = MultiFieldQueryParser.parse(Version.LUCENE_29,queryWord, fields, flags, LocalFileIndexBuilder.ANALYZER1);
				h = searcher.search(q); //, sort
			}
			int sRow = 0;
			int eRow = h.length();
			if(startRow >= 0){
				sRow = startRow;
			}
			if(endRow <= h.length()) {
				eRow = endRow;
			}
			for(int i = sRow; i < eRow; i++) {
				Document doc = h.doc(i);
				ret.add(doc);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				searcher.close();
				
			} catch (IOException e) {
			}
		}
		return ret;
	}
	
	/** 结果总数 */
	public int getRowCount(String queryWord, String[] fields) {
		int ret = 0;
		Searcher searcher = null;
		
		try {	
			searcher = new IndexSearcher(this.indexReader);
			BooleanClause.Occur[] flags = new BooleanClause.Occur[fields.length];
			for(int i = 0; i < flags.length; i++) {
				flags[i] = BooleanClause.Occur.SHOULD;
			}
			Query q = MultiFieldQueryParser.parse(Version.LUCENE_29, queryWord, fields, flags, LocalFileIndexBuilder.ANALYZER2);
			Hits h = searcher.search(q);
			if(h.length() == 0) {
				q = MultiFieldQueryParser.parse(Version.LUCENE_29, queryWord, fields, flags, LocalFileIndexBuilder.ANALYZER1);
				h = searcher.search(q);
			}
			ret = h.length();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				searcher.close();
			} catch (IOException e) {
			}
		}
		return ret;
	}
	
	public void close() {
		try {
			this.indexReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getIndexStorePath() {
		return indexStorePath;
	}

	public void setIndexStorePath(String indexStorePath) {
		this.indexStorePath = indexStorePath;
	}

	public void deleteIndexByIndex(String idxStr) {
	    synchronized (indexStorePath) {
	        try {
	          IndexReader indexReader = IndexReader.open(indexStorePath);
	          Term term = new Term("id", idxStr);
	          indexReader.deleteDocuments(term);
//	          indexReader.
//	          while (it.hasNext()) {
//	            indexReader.deleteDocument(((LuceneItem) it.next()).getDocId());
//	          }
	          indexReader.close();
	        } catch (IOException e) {
	          logger.error(e);
	        }
	      }
	}
	
	
}
